package com.audaque.springboot.foshanupload.casclientautoconfigsupport.controller;

import com.audaque.springboot.foshanupload.casclientautoconfigsupport.component.ServerUrlProvider;
import com.audaque.springboot.foshanupload.casclientautoconfigsupport.properties.ServerProperties;
import com.audaque.springboot.foshanupload.casclientautoconfigsupport.properties.ServiceProperties;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/sso")
public class SsoController {


    @Autowired
    private ServerUrlProvider serverUrlProvider;
    @Autowired
    private ServerProperties serverProperties;

    @Autowired
    private ServiceProperties serviceProperties;

    @GetMapping("/serverLoginUrl")
    public String serverLoginUrl() {
        TransmittableThreadLocalCurrentUser current = TransmittableThreadLocalCurrentUser.getCurrentUser();
        //已登录则直接去首页
        if (current != null && StringUtils.isNotBlank(current.getUsername())) {
            String serviceRedirectUrl = serviceProperties.getServiceRedirectUrl();
            return serviceRedirectUrl;
        }
        //未登录则去登录
        String serverLoginUrl = serverUrlProvider.getServerLoginUrl();
        return serverLoginUrl;
    }

    @GetMapping("/serverLogoutUrl")
    public String serverLogoutUrl() {
        TransmittableThreadLocalCurrentUser current = TransmittableThreadLocalCurrentUser.getCurrentUser();
        //已登出则直接去首页
        if (current == null || StringUtils.isBlank(current.getUsername())) {
            String serviceRedirectUrl = serviceProperties.getServiceRedirectUrl();
            return serviceRedirectUrl;
        }
        //未登出则去登出
        String serverLogoutUrl = serverUrlProvider.getServerLogoutUrl();
        return serverLogoutUrl;
    }


    @GetMapping("/login")
    public TransmittableThreadLocalCurrentUser login(HttpSession session, @Parameter(required = true) String serviceRedirectUrl, HttpServletResponse response) throws IOException {

        //认证完成后回调到客户端
        TransmittableThreadLocalCurrentUser currentUser = TransmittableThreadLocalCurrentUser.getCurrentUser();

        //客户端封装响应
        if (currentUser != null && StringUtils.isNotBlank(currentUser.getUsername())) {
            if (serviceRedirectUrl != null) {
                // 单点登录成功后，重定向到前台url
                //."text/html;charset=UTF-8"
                response.setHeader(HttpHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_HTML_VALUE);
                response.sendRedirect(serviceRedirectUrl);
                //自定义Cookie
                /*
                Cookie cookie = new Cookie("X-Context", Base64Encoder.encodeStr(JSONUtil.toJsonStr(transmittableThreadLocalCurrentUser).getBytes(StandardCharsets.UTF_8), false, false));
                URL urlToRedirect = new URL(serviceRedirectUrl);
                cookie.setDomain(urlToRedirect.getHost());
                cookie.setPath("/");
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
                */
                return null;
            } else {
                return currentUser;
            }
        }
        return null;
    }


    @GetMapping("/logout")
    public void logout(HttpSession session, @Parameter(required = true) String serviceRedirectUrl, HttpServletResponse response) throws IOException {
        //服务端已清除session
        //清除本地session
        session.invalidate();
        if (serviceRedirectUrl != null) {
            // 单点登出成功后，重定向到前台url
            //."text/html;charset=UTF-8"
            response.setHeader(HttpHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_HTML_VALUE);
            response.sendRedirect(serviceRedirectUrl);
        }

    }


}
